import styles from './index.module.scss'
import { useRef, useState, useEffect } from 'react'
import { useCountDown } from '@/utils/hooks'
import Input from './input'
import Button from '../button'
import cm from 'classnames'
import { signIn, checkCodeValid, sendCode } from '@/api/login'
import { cncryptionCipher, encryptParams } from './encode'
import EventBus from '@/utils/emitter'
import { injectScript } from '@/utils/utils'
import { taskFinished } from '@/api/score'
import { useSetUserInfo } from '@/utils/hooks'
// 获取易盾token
const getYiDunToken = async () => {
  await injectScript('/js/yidun-web.js', 'yidun')
  const neg = createNEGuardian({ appId: 'YD00766955874482', timeout: 10000 })
  const result = await neg.getToken()
  return result?.token || ''
}
const pattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/

const Index = props => {
  const { email: medium, toSuccess,setLogin } = props
  const submitRef = useRef(null)
  const [_, setUserInfo] = useSetUserInfo()
  const [acceptEmail, setAcceptEmail] = useState(false) //是否接收来自星视界的邮件
  const [firstPwd, setFirstPwd] = useState('')
  const [secondPwd, setSecondPwd] = useState('')
  const [second, isStart, startRun] = useCountDown(60)
  const [success, setSuccess] = useState(false)
  const [isLoading, setLoading] = useState(false)
  const [error, setError] = useState({
    pass: true,
    msg: ''
  })
  const [code, setCode] = useState('')
  // 发送验证码
  const getCode = () => {
    startRun()
    sendCode(medium)
  }

  // 验证输入密码的合法性
  const isValid = async () => {
    const passd = pattern.test(firstPwd)
    if (!passd) {
      return {
        pass: false,
        msg: '密码格式有误!!!'
      }
    }
    if (firstPwd !== secondPwd) {
      return {
        pass: false,
        msg: '两次密码不一致!!!'
      }
    }
    if (!code) {
      return {
        pass: false,
        msg: '验证码无效'
      }
    }
    const res = await checkCodeValid({ medium, code })
    if (res.code) {
      return {
        pass: false,
        msg: '验证码错误'
      }
    }
    return {
      pass: true
    }
  }

  // 提交注册
  const submit = async () => {
    if (isLoading) {
      return
    }
    const errors = await isValid()
    setError(errors)
    if (!errors.pass) {
      return
    }
    setLoading(true)
    EventBus.emit('toggleRobot', false, true)
  }
  //验证注册
  const handleLogin = async () => {
    const ydtoken = await getYiDunToken()
    const params = {
      acceptEmail: acceptEmail,
      medium: medium,
      code: code,
      password: cncryptionCipher(firstPwd),
      ydtoken
    }
    // 如果存在邀请人id，则填入数据
    const inviteId = localStorage.getItem('invite_code')
    if (inviteId) {
      params.inviterUserId = parseInt(inviteId)
    }
    const MuId =  localStorage.getItem('MuId')
    const { body, headers } = await encryptParams(params)
    const res = await signIn(body, { headers:{...headers,MuId:MuId ? MuId: undefined} })
    setLoading(false)
    if (!res.code) {
      setUserInfo(res.data.token)
      localStorage.setItem('token', res.data.token)
      localStorage.setItem('email', medium)
      taskFinished({
        completionStatus: 1,
        ydtoken: ''
      })
      setLogin(false)
      toSuccess()
    } else {
      setSuccess(false)
      setError({
        pass: false,
        msg: res?.msg || '注册失败，请稍后重新尝试。'
      })
    }
  }

  useEffect(() => {
    const enterClick = e => {
      if (e.keyCode === 13) {
        submitRef.current.click()
      }
    }
    window.addEventListener('keydown', enterClick)

    // 提交注册
    EventBus.on('signRobotSuccess', async () => {
      EventBus.emit('toggleRobot', false, false)
      setSuccess(true)
    })
    return () => {
      window.removeEventListener('keydown', enterClick)
      EventBus.offAll('signRobotSuccess')
    }
  }, [])

  useEffect(() => {
    if (!success) {
      return
    }
    handleLogin()
  }, [success])

  const addonCode = isStart ? (
    <span className={styles.codeText}>{second}s后可重发</span>
  ) : (
    <span className={styles.getCode} onClick={getCode}>
      获取验证码
    </span>
  )

  return (
    <div className={styles.signIn}>
      <p className={styles.email}>{medium}</p>
      <p className={styles.setPwd}>设置密码</p>
      <p className={styles.tips}>提示：须是6-20个英文字母、数字，且以上两种必须都包含</p>
      <Input placeholder="请输入密码" type="password" className={styles.pwd} onChange={data => setFirstPwd(data)} />
      <Input placeholder="请再次输入密码" type="password" onChange={data => setSecondPwd(data)} />
      <p className={styles.checkEmail}>邮箱验证</p>
      <Input placeholder="输入验证码" type="text" addonAfter={addonCode} onChange={data => setCode(data)} />
      {isStart ? (
        <p className={styles.tips} style={{ marginTop: 8, marginBottom: 4 }}>
          提示：验证码将发送至您的邮箱，15分钟内有效
        </p>
      ) : null}
      {!error.pass ? <p className={styles.error}>{error.msg}</p> : null}
      <Button
        hover="opacity"
        ref={submitRef}
        className={cm(styles.btn, isLoading ? styles.btnLoading : '')}
        onClick={submit}
      >
        {isLoading ? '账户创建中...' : '创建账户并登录'}
      </Button>
      <p className={styles.agree}>
        <span
          className={cm(styles.radio, { [styles.radioActive]: acceptEmail })}
          onClick={() => setAcceptEmail(!acceptEmail)}
        ></span>
        <span>不接收星视界的精彩内容推荐邮件</span>
      </p>
    </div>
  )
}

export default Index
